package cn.itcast.netty.basic;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer  {
    public static void main(String[] args) throws Exception{
        //1.创建一个线程组，接收客户端连接
        NioEventLoopGroup boss = new NioEventLoopGroup();

        //2.创建线程组，处理网络操作
        NioEventLoopGroup worker = new NioEventLoopGroup();

        //3.创建服务器端启动助手，配置参数
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(boss,worker)//设置二个线程组
                .channel(NioServerSocketChannel.class)//使用NioEventLoopGroup作为服务器通道的实现
                .option(ChannelOption.SO_BACKLOG,128)//设备线程队列中等待连接的的个数
                .childOption(ChannelOption.SO_KEEPALIVE,true) //保持活动的连接状态
                .childHandler(new ChannelInitializer<SocketChannel>() {//创建通道初始化对象
                    public void initChannel(SocketChannel sc){    //往pipeline链中添加handler类
                        sc.pipeline().addLast(new NettyServerHandler());
                    }
                });
        System.out.println("Server is ready....");

        ChannelFuture cf = serverBootstrap.bind(9999).sync();//绑定端口   非阻塞
        System.out.println("....Servr is starting...");
        //关闭通道，关闭线程组
        cf.channel().closeFuture().sync();  //异步
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }
}
